const Koa = require('koa'),
  app = new Koa()
var logger = require('koa-logger')
  , json = require('koa-json')
  , onerror = require('koa-onerror');

const fs = require('fs'),
  getUserInfo = require('./config/getUserInfo'),
  jwt = require('koa-jwt'),
  { JWT_SECURITY_KEY } = require('./config/security'),
  bodyparser = require('koa-bodyparser')

const index = require('./routes/index');
const users = require('./routes/users');

const Database = require('better-sqlite3'),
  path = require('path'),
  dbRelate = path.join('./models', 'app.db'),
  db = new Database(dbRelate)

// error handler
onerror(app);

// global middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json());
app.use(logger());
app.use(getUserInfo);
app.use(jwt({ secret: JWT_SECURITY_KEY })
  .unless({ path: [/^\/api\/users\/check$/] })
)

app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log('%s %s - %s', ctx.method, ctx.url, ms);
});

app.use(require('koa-static')(__dirname + '/public'));

// routes definition
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());

//init 用户的文件包
const initDir = () => {
  const users = db.prepare('select * from users').all()
  for (let i = 0; i < users.length; i++) {
    if (!fs.existsSync(`./server/${users[i].id}`)) {
      fs.mkdirSync(`./server/${users[i].id}`)
    }
  }
}

initDir()

app.listen(8080, () => {})

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app;
